package org.pine.start.handler;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.pine.api.enums.ResultCodeEnum;
import org.pine.common.beans.Result;
import org.pine.common.exception.PineException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Iterator;
import java.util.Set;

import static org.springframework.http.HttpStatus.OK;

/**
 * 全局异常处理
 *
 * @author pine manage
 * @since 2024-08-14
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

//    /**
//     * sa-toke权限校验
//     */
//    @ExceptionHandler(NotPermissionException.class)
//    @ResponseStatus(OK)
//    public ResultVo<Boolean> handleNotPermissionException(NotPermissionException exception) {
//        log.error("NotPermissionException occurred ! ", exception);
//        return ResultVo.error(ExceptionCodeEnum.USER_NOT_AUTHORIZED.getCode(), exception.getMessage());
//    }
//
//    /**
//     * sa-toke角色校验
//     */
//    @ExceptionHandler(NotRoleException.class)
//    @ResponseStatus(OK)
//    public ResultVo<Boolean> handleNotRoleException(NotRoleException exception) {
//        log.error("NotRoleException occurred ! ", exception);
//        return ResultVo.error(ExceptionCodeEnum.USER_ROLE_ERROR.getCode(), exception.getMessage());
//    }

    /**
     * 违反约束，jakarta定义与自定义校验
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(OK)
    Result<Boolean> handleConstraintViolationException(ConstraintViolationException exception) {
        log.warn("handleConstraintViolationException occurred ! ", exception);
        Set<ConstraintViolation<?>> constraintViolations = exception.getConstraintViolations();
        Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
        StringBuilder stringBuffer = new StringBuilder();
        while (iterator.hasNext()) {
            stringBuffer.append(" ").append(iterator.next().getMessage()).append(";");
        }
        return Result.error(ResultCodeEnum.VALID_EXCEPTION, stringBuffer.toString());
    }

    /**
     * 参数无效，如JSON请求参数违反约束
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(OK)
    Result<Boolean> handleMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
        log.warn("handleMethodArgumentNotValidException occurred ! ", exception);
        StringBuilder stringBuffer = new StringBuilder();
        for (FieldError error : exception.getBindingResult().getFieldErrors()) {
            stringBuffer.append(error.getDefaultMessage()).append(";");
        }
        return Result.error(ResultCodeEnum.ARGS_INVALID_EXCEPTION, stringBuffer.toString());
    }

    /**
     * 业务异常
     *
     * @param exception 业务异常
     * @return 响应
     */
    @ResponseStatus(OK)
    @ExceptionHandler(PineException.class)
    public Result<Boolean> handleCustomException(PineException exception) {
        log.error("业务异常：{}", exception.getMessage(), exception);
        return Result.error(exception.getCode(), exception.getMessage());
    }

    /**
     * 其他异常处理
     *
     * @param exception 未处理异常
     * @return ResponseEntity
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(OK)
    public Result<Boolean> handleRuntimeException(RuntimeException exception) {
        log.error("系统内部异常", exception);
        return Result.error(ResultCodeEnum.UNEXPECTED_EXCEPTION.getCode(), exception.getMessage());
    }

    /**
     * 全局异常
     *
     * @param exception 全局异常
     * @return 响应
     */
    @ResponseStatus(OK)
    @ExceptionHandler(Exception.class)
    public Result<Boolean> handleException(Exception exception) {
        log.error("未知异常：{}", exception.getMessage(), exception);
        return Result.error(ResultCodeEnum.UNEXPECTED_EXCEPTION.getCode(), exception.getMessage());
    }
}
